﻿using Application.Common.Interfaces;
using AutoMapper;
using Common.Attributes;
using Domain.Entities;
using MediatR;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using Microsoft.EntityFrameworkCore;
using System.Text.Json.Serialization;
using Common.Events;

namespace Application.Features.Roles.Commands.Update;

#nullable disable

/// <summary>
/// 修改角色状态
/// </summary>
[Map(typeof(Role))]
[Description("修改状态")]
[GroupDescription(("角色管理"))]
public class UpdateRoleStatusCommand : IRequest<bool>
{
    /// <summary>
    /// 角色唯一标识
    /// </summary>
    [Required(ErrorMessage = "角色唯一标识必填")]
    [JsonIgnore]
    public long RoleId { get; set; }

    /// <summary>
    /// 并发标记
    /// </summary>
    [Required(ErrorMessage = "并发标记必填的")]
    public string ConcurrencyStamp { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class UpdateRoleStatusCommandHandler : IRequestHandler<UpdateRoleStatusCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public UpdateRoleStatusCommandHandler(
        IApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(UpdateRoleStatusCommand request, CancellationToken cancellationToken)
    {
        var role = await _context.Roles
            .SingleOrDefaultAsync(x => x.Id == request.RoleId && x.ConcurrencyStamp == request.ConcurrencyStamp, cancellationToken);
        
        _mapper.Map(request, role);
        role.IsActived();
        role.AddDomainEvent(new UpdatedEvent<Role>(role));
        _context.Roles.Update(role);

        return true;
    }
}
